C++17 introduced as_const
: a helper function that converts a value to its corresponding const value succinctly and more
explicitly.
This is usually done to force an overloaded function call on a non-const object to resolve to the const alternative. Or to instantiate a template
with a const type rather than the original non-const one.
This rule detects casts that can be replaced by as_const
.
Noncompliant code example
void fn(std::vector<int>& vec);
void fn(const std::vector<int>& vec);
void constFCaller() {
std::vector<int> vec;
// Set the content of vec
// ...
fn(static_cast<const std::vector<int>&>(vec)); // Noncompliant
}
Compliant solution
void fn(std::vector<int>& vec);
void fn(const std::vector<int>& vec);
void constFCaller() {
std::vector<int> vec;
// Set the content of vec
// ...
fn(as_const(vec)); // Compliant
}